package cn.hamster3.mc.plugin.ball.bungee.listener;

import cn.hamster3.mc.plugin.ball.bungee.util.BallBungeeCordUtils;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.ball.common.event.BallActions;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerLogoutEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerPostConnectServerEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerPreConnectServerEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;

public class UpdatePlayerInfoListener implements Listener {
    public static final UpdatePlayerInfoListener INSTANCE = new UpdatePlayerInfoListener();

    private UpdatePlayerInfoListener() {
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onServerConnect(ServerConnectEvent event) {
        ProxiedPlayer player = event.getPlayer();
        BallPlayerInfo playerInfo = BallBungeeCordUtils.getPlayerInfo(player, true);
        playerInfo.setGameServer(event.getTarget().getName());
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerPreConnectServer.name(),
                new BallPlayerPreConnectServerEvent(playerInfo, playerInfo.getGameServer(), event.getTarget().getName())
        );
        BallBungeeCordUtils.uploadPlayerInfo(playerInfo);
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onServerConnected(ServerConnectedEvent event) {
        ProxiedPlayer player = event.getPlayer();
        BallPlayerInfo playerInfo = BallBungeeCordUtils.getPlayerInfo(player, true);
        playerInfo.setGameServer(event.getServer().getInfo().getName());
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerPostConnectServer.name(),
                new BallPlayerPostConnectServerEvent(playerInfo)
        );
        BallBungeeCordUtils.uploadPlayerInfo(playerInfo);
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerDisconnect(PlayerDisconnectEvent event) {
        ProxiedPlayer player = event.getPlayer();
        BallPlayerInfo playerInfo = BallBungeeCordUtils.getPlayerInfo(player, false);
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerLogout.name(),
                new BallPlayerLogoutEvent(playerInfo)
        );
        BallBungeeCordUtils.uploadPlayerInfo(playerInfo);
    }
}
